class Api::V1::UsersController < Api::V1::BaseController
  before_action :authenticate_request!, except: :index

  def index
    render json: User.all
  end

  def show
    @user = User.find(params[:id])
    render json: @user, status: 200
  end

  def create
    begin
      @user = User.new(create_params)
      authorize @user
      @user.save!
      render json: @user, status: 201
    rescue ActiveRecord::StatementInvalid
      @user.errors.add(:exec_error, '数据库错误，请联系管理员')
      error_render(@user, 403)
    rescue => err
      error_render(err.record, 403)
    end
  end

  def update
    begin
      @user = User.find(params[:id])
      @user.update_attributes!(create_params)
      render json: @user, status: 200
    rescue => err
      error_render(err.record, 403)
    end
  end

  def destroy
    begin
      @user = User.find(params[:id])
      @user.destroy!
      render status: :no_content
    rescue ActiveRecord::RecordNotFound
      render status: :not_found
    rescue
      render status: :forbidden
    end
  end

  private

  def create_params
#    params.require(:data).permit(:type, :id, attributes: [:username, :email, :phone_num, :password, :password_confirmation, :activity, :role_id, :company_id])
    params_parse(params)
  end

  def relationship_role
    params.require(:data).require(:relationships).require(:role).require(:data).permit(:id, :type)
  end

  def realtionship_company
    params.require(:data).require(:relationships).require(:company).require(:data).permit(:id, :type)
  end

end
